<?php
/**
 * @author hjj
 * 京东jos ECLP沧海系统 供应商订单
 * 电商平台负责申报支付单，供应商申报订单和清单
 */

namespace App\Service\OrderService\OrderRouteService;

use App\Service\Code\Normal;
use App\Model\PssModel\OrderSupplier;
use Service\AppService\IdService;
use App\Service\OrderService\BaseSupplierRouterService;
use App\Service\VendorClient\ShopjdApi\ShopEclpClient;
use App\Model\CommodityModel\SupplierCommodity;

class Shopjdeclp extends BaseSupplierRouterService {

    /**
     * 创建订单
     * @param array $param
     * @return mixed
     */
    public function createOrder($param = []) {
        //下单商品重组
        $supplierGoodsInfo = $param['supplierGoodsInfo'];
        $userGoodsList     = $supplierGoodsInfo['userGoodsList'];
        $goodsList         = $supplierGoodsInfo['goodsList'];
        $orderItems        = [];
        $supplierCode      = $supplierGoodsInfo['supplierCode'];
        //按照仓区进行拆单
        $defaultStockGroupGoodsList = [];
        foreach ($goodsList as $item) {
            $defaultStockGroupGoodsList[$item['defaultStock']][] = $item;
            unset($item);
        }

        //下游是否申报
        $isDelare = (
            (isset($param['order']['isOrderDeclare']) && $param['order']['isOrderDeclare'] == 1) ||
            (isset($param['order']['isPayDeclare']) && $param['order']['isPayDeclare'] == 1)
        ) ? true : false;
        //是否云仓商城
        $isShop = isset($param['order']['isSplitOrder']) && $param['order']['isSplitOrder'] == 1 ? true : false;

        foreach ($defaultStockGroupGoodsList as $item) {
            $currentGoods          = current($item);
            $supplierCommodityType = $currentGoods['supplierCommodityType'];

            //重新合并每一个仓库商品
            $orderGoods = [];
            foreach ($item as $goods) {
                $orderGoods = array_merge($orderGoods, $userGoodsList[$goods['skuCode']]);
                unset($goods);
            }

            //生成供应商主单号
            $param['order']['supplier_psn'] = OrderSupplier::instance()->getCreateOrderSn($supplierCode);
            $param['order']['supplier_csn'] = IdService::instance()->getOtherID();

            //防止订单号重复问题,下游已申报，则使用下游的订单号作为中台子单号
            if ($isDelare && !$isShop && $supplierCommodityType != GOODS_TYPE_YBMY) {
                $param['order']['supplier_dsn'] = $param['order']['orderSn'];
            } else {
                $param['order']['supplier_dsn'] = IdService::instance()->getOtherID();
            }

            $param['order']['goods']          = $orderGoods;
            $param['order']['isQueryExpress'] = 1;
            $res                              = OrderSupplier::instance()->getSupplierCreateOrderData($param);
            if ($res['code'] != Normal::SUC) {
                return $res;
            }
            $orderItems[] = $res['data'];
        }

        return Normal::returnCode(Normal::SUC, "获取成功", [
            'supplierCode' => $supplierCode,
            'orderItems'   => $orderItems
        ]);
    }

    /**
     * 订单支付
     * @param array $param
     * @return mixed
     */
    public function orderPay($param = []) {
        //根据skucode 查询净重和毛重
        $orderGoods      = $param['orderGoods'];
        $goodsIdList     = array_column($orderGoods, 'goods_id');
        $weightArr       = SupplierCommodity::query()->from((new SupplierCommodity())->getTable() . ' as scs')
            ->join('commodityarchives_s2b as cas', 'cas.ID', '=', 'scs.CommodityArchivesID')
            ->whereIn('cas.ID', $goodsIdList)->select([
                  'cas.ID as goods_id',
                  'scs.SupplierCommodityNetWeight as net_weight',
                  'cas.Weight as weight',
             ])->get()->toArray();
        $weightByGoodsId = array_column($weightArr, null, 'goods_id');
        foreach ($param['orderGoods'] as &$orderGood) {
            if (isset($weightByGoodsId[$orderGood['goods_id']])) {
                $goodsWeight             = $weightByGoodsId[$orderGood['goods_id']];
                $orderGood['weight']     = $goodsWeight['weight'];
                $orderGood['net_weight'] = $goodsWeight['net_weight'];
            }
            unset($orderGood);
        }
        return $this->callSdkApi(ShopEclpClient::class, $param['apiBody'])->createOrder($param);
    }

    /**
     * 订单取消
     * @param array $param
     * @return mixed
     */
    public function orderCancel($param = []) {
        return Normal::returnCode(Normal::SUC, "处理完成");
    }

    /**
     * 订单售后
     * @param array $param
     * @return mixed
     */
    public function orderAfterSale($param = []) {
        return $this->callSdkApi(ShopEclpClient::class, $param['apiBody'])->cancelOrder($param);
    }


    /**
     * 商品列表查询接口
     * @param array $param
     * @return mixed
     */
    public function queryGoodsList($param = []) {
        return Normal::returnCode(Normal::SUC, "获取成功", [
            'total' => 0,
            'list'  => []
        ]);
        $res = $this->callSdkApi(ShopEclpClient::class, $param['apiBody'])->{__FUNCTION__}($param['queryBody']);
        if ($res['code'] != Normal::SUC) {
            return $res;
        }
        return Normal::returnCode(Normal::SUC, "获取成功", [
            'total' => $res['data']['total'],
            'list'  => $res['data']['list']
        ]);
    }

    /**
     * 查询物流
     * @param array $param
     * @return mixed
     */
    public function queryOrderExpress($param) {
        $queryBody = $param['queryBody'];
        $orderID   = $queryBody['orderID'];
        $orderInfo = OrderSupplier::instance()->info(['id' => $orderID, 'company_id' => $queryBody['supplierID']], ['thirdpart_order_sn', 'cd']);
        if (empty($orderInfo)) {
            return Normal::returnCode(Normal::FAIL, "订单信息不存在，请核对！");
        }
        $res = $this->callSdkApi(ShopEclpClient::class, $param['apiBody'])->{__FUNCTION__}($orderInfo);
        if ($res['code'] != Normal::SUC) {
            if (isset($res['data']['exception'])) {
                //这里要修改状态
                OrderSupplier::instance()
                    ->where(['id' => $orderID, 'company_id' => $queryBody['supplierID']])
                    ->update([
                         'is_query_express'     => 0,
                         'order_decalre_status' => 2,//申报失败
                         'order_decalre_result' => $res['data']['exception']
                     ]);
                return Normal::returnCode(Normal::FAIL, '申报失败');
            }
            return $res;
        }
        $expressName = $res['data']['expressName'] ?? '';
        $expressNo   = $res['data']['expressNo'] ?? '';
        if (empty($expressName) || empty($expressNo)) {
            return Normal::returnCode(Normal::FAIL, "订单未发货");
        }
        return Normal::returnCode(Normal::SUC, "已发货", [
            'expressInfo' => [
                'express_name' => $expressName,
                'express_sn'   => $expressNo,
            ]
        ]);
    }
}